/****************************************************
 * 创建人：@author fengxin    
 * 创建时间: 2019/12/19/11:40
 * 项目名称: risk
 * 文件名称: StreamerServer.java
 * 文件描述: 
 *
 * All rights Reserved, Designed By 投资交易团队
 * @Copyright:2016-2019
 *
 ********************************************************/
package com.learn.zmq.stream;

import org.zeromq.SocketType;
import org.zeromq.ZContext;
import org.zeromq.ZMQ;
import zmq.Msg;

import java.util.HashSet;
import java.util.Set;

/**
 * 包名称：com.ysstech.zmq.stream
 * 类名称：StreamerServer
 * 类描述：基于zmq的STREAM连接模式构建的简单Http服务器  可通过 {@link <link href=http://localhost:12309/>}访问
 * 参考文档：{@link <link href=http://api.zeromq.org/4-0:zmq-socket/>}
 * 创建人：@author fengxin
 * 创建时间：2019/12/19/11:40
 */
public class StreamHttpServer {

    public static void main(String[] argv) {
        try (ZContext ctx = new ZContext()) {
            ZMQ.Socket streamer = ctx.createSocket(SocketType.STREAM);
            streamer.setLinger(-1);
            System.out.println("StreamServer Linger: " + streamer.getLinger());
            // 绑定到端口
            streamer.bind("tcp://*:12309");
            // 获取实际的server地址
            String host = streamer.getLastEndpoint();

            System.out.println("server address is: "+host);
            byte[] peerId;
            byte[] peerIdTmp;
            byte[] zero = new byte[0];
            int count = 1;
            String peerIdStr;
            String peerIdStrTmp="";

            Set<String> peerSet = new HashSet<>();

            while (true) {
                // 第一个msg是identity
                Msg msg = zmq.ZMQ.recv(streamer.base(), 0);
                peerId = msg.data();
                peerIdStr = new String(peerId,ZMQ.CHARSET);
                String peerAddr = msg.getMetadata().get("Peer-Address");
                System.out.println("msg size: "+msg.size());

                if (peerId.length==0) {
                    continue;
                }

                System.out.println("received "+count+"-th request from "+peerAddr);
                String httpResponse = "HTTP/1.0 200 OK\r\n"+
                "Content-Type: text/plain\r\n"+
                "\r\n"+
                "Hello, Client!";
                streamer.send(peerId,ZMQ.SNDMORE);
                streamer.send(httpResponse,ZMQ.SNDMORE);
                streamer.send(peerId,ZMQ.SNDMORE);
                streamer.send(zero,ZMQ.SNDMORE);
                count++;
            }
        }

    }
}